import React, { useState } from 'react'
import { CloseCircleOutlined, PoweroffOutlined, UserOutlined, ExclamationCircleOutlined, CloseSquareOutlined } from '@ant-design/icons'
import { Dropdown, Menu, Space, message } from 'antd';
import { NavigateFunction, useNavigate } from 'react-router-dom';
import style from './index.module.less'
import { useDispatch, useSelector } from 'react-redux';
import { clearWindow } from '@redux/actions/tab';
import ModifyPasswordModal from './modifyPasswordModal'
import { Dispatch } from 'redux';
import { INIT_BASIC_STATE } from '@redux/reducers/basic';
import TabBar from './tabBar'
import { awaitWrap } from '@src/assets/js/tool';
import { logoutRequest } from './ajax'
import { setToken, setUserInfo, setUncompleteMessage, setUncompleteMessageNum } from '@redux/actions/basic';
import { UserInfo } from '@src/components/schema/basic';


async function logoutHandle (dispatch: Dispatch, navigate: NavigateFunction) {
  const hide = message.loading('退出中', 120)
  const [e] = await awaitWrap(logoutRequest())
  hide()
  if (e === null) {
    dispatch(clearWindow())
    dispatch(setToken(''))
    dispatch(setUserInfo({} as UserInfo))
    dispatch(setUncompleteMessage([]))
    dispatch(setUncompleteMessageNum(0))
    navigate('/login')
  }
}

function selectMenu (k: string, navigate: NavigateFunction, dispatch: Dispatch, setVisible: (v: boolean) => void) {
  if (k === 'logout') {
    logoutHandle(dispatch, navigate)
  } else if (k === 'modifyPassword') {
    setVisible(true)
  }
}

function Main() {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const [visible, setVisible] = useState(false)
  const { userInfo } = useSelector((state: { basic: INIT_BASIC_STATE }) => {
    return {
      userInfo: state.basic.userInfo
    }
  })
  const menu = (
    <Menu onClick={v => selectMenu(v.key, navigate, dispatch, setVisible)} items={[
      { label: '修改密码', key: 'modifyPassword' },
      { type: 'divider' },
      { label: '退出', key: 'logout', icon: <PoweroffOutlined className={style['out-icon']} /> }
    ]}>
    </Menu>
  )
  return (
    <div className={style.header}>
        <ModifyPasswordModal visible={visible} hide={() => setVisible(false)} />
        <div className={style['header-content']}>
          <TabBar />
          <div className={style['other-block']}>
            <div className={style['close-all']} onClick={() => dispatch(clearWindow(true))}>
              <CloseSquareOutlined />
            </div>
            <Dropdown overlay={menu} trigger={['click']}>
              <div className={style.person}>
                <div className={style.person__icon}>
                  <div className={style.person__icon__bg}>
                    <UserOutlined />
                  </div>
                </div>
                <span className={style.person__name}>{userInfo.realname || ''}</span>
              </div>
            </Dropdown>
          </div>
        </div>
      </div>
  )
}

export default Main
